﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System;
using System.IO;
using System.Text;
using System.Collections;
using Newtonsoft.Json;
using WindowsFormsApp1.Properties;

namespace WindowsFormsApp1
{



    public partial class Form1 : Form
    {

        [Serializable]
        public class MySettings
        {
            public string BlackProgramDir { get; set; }
            public string TargetDir { get; set; }

            public Dictionary<string, bool> ServerItems;
        }



        private List<ServerItemControl> itemControls = new List<ServerItemControl>();
        public Form1()
        {
            InitializeComponent();
        }

        private void BlackProgramButton_Click(object sender, EventArgs e)
        {
            string SelectedPath = GetChooseFolderPath();
            if (SelectedPath != "")
            {
                this.BlackProgramDirText.Text = SelectedPath;
            }

        }

        private void TargetButton_Click(object sender, EventArgs e)
        {
            string SelectedPath = GetChooseFolderPath();
            if (SelectedPath != "")
            {
                this.targetDirText.Text = SelectedPath;
            }
        }

        private string GetChooseFolderPath()
        {
            // 创建 FolderBrowserDialog 实例
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            // 可选：设置对话框的初始目录（默认是"我的电脑"或上次访问的目录）
            //folderBrowserDialog.InitialDirectory = @"C:\";
            folderBrowserDialog.SelectedPath = @"C:\";
            // 可选：设置对话框标题（默认是"浏览文件夹"）
            folderBrowserDialog.Description = "请选择文件夹";

            // 显示对话框并检查用户是否点击了"确定"
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                // 返回用户选择的文件夹路径
                return folderBrowserDialog.SelectedPath;

            }
            // 用户取消了选择
            return string.Empty;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadData();
        }
        private void Form1_FormClosing(object sender, EventArgs e)
        {
            SaveData();
        }
        private void AddButton_Click(object sender, EventArgs e)
        {
            // 创建新的ItemControl
            var newItem = new ServerItemControl();

            // 添加到列表和面板
            itemControls.Add(newItem);
            flowLayoutPanel1.Controls.Add(newItem);

            // 更新标签文本显示序号
            newItem.Init();
        }

        private void RemoveButton_Click(object sender, EventArgs e)
        {
            if (itemControls.Count > 0)
            {
                // 获取最后一个控件
                var lastItem = itemControls[itemControls.Count - 1];

                // 从面板和列表中移除
                flowLayoutPanel1.Controls.Remove(lastItem);
                itemControls.RemoveAt(itemControls.Count - 1);

                // 释放资源
                lastItem.Dispose();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

            string sourceDir = this.BlackProgramDirText.Text;    // 源目录
            string destDir = this.targetDirText.Text;        // 目标目录
            string LoginServerName = "MMOARPGLoginServer";        // 新名称
            string GateServerName = "MMOARPGGateServer";        // 新名称
            string DBServerName = "MMOARPGDBServer";        // 新名称
            string CenterServerName = "MMOARPGCenterServer";        // 新名称
            string oldName = "BlankProgram";        // 要替换的旧名称

            this.textBox1.Text = "";
            if (!Directory.Exists(sourceDir))
            {
                this.textBox1.Text += $"源目录不存在" + "\n";
                return;
            }

            if (itemControls.Count > 0)
            {
                foreach (var serverItemControl in itemControls)
                {
                    string serverName = serverItemControl.GetServerName();
                    bool fugai = serverItemControl.GetCheckState() == CheckState.Checked;
                    this.textBox1.Text += $"处理文件 {serverName}" + "\n";
                    CopyAndRenameDirectory(sourceDir, destDir + serverName, oldName, serverName, fugai);
                }

            }
            else
            {
                this.textBox1.Text += $"未配置Server" + "\n";
            }

            this.SaveData();


        }

        private void CopyAndRenameDirectory(string sourcePath, string destPath, string oldStr, string newStr, bool Fugai = false)
        {

            //判断目标目录文件夹是否存在
            if (Directory.Exists(destPath))
            {
                if (Fugai)
                {
                    Directory.Delete(destPath, true);
                }
                else
                {
                    return;
                }
            }
            // 创建目标目录
            Directory.CreateDirectory(destPath);

            // 复制所有文件
            foreach (string file in Directory.GetFiles(sourcePath))
            {
                string fileName = Path.GetFileName(file);
                string newFileName = fileName.Replace(oldStr, newStr);
                string destFile = Path.Combine(destPath, newFileName);
                File.Copy(file, destFile, true);
                if (fileName != "BlankProgram.ico")
                {
                    // 处理文件内容替换
                    ProcessFileContent(destFile, oldStr, newStr);
                }
            }

            // 递归复制子目录
            foreach (string dir in Directory.GetDirectories(sourcePath))
            {
                string dirName = Path.GetFileName(dir);
                string newDirName = dirName.Replace(oldStr, newStr);
                string destDirPath = Path.Combine(destPath, newDirName);

                CopyAndRenameDirectory(dir, destDirPath, oldStr, newStr);
            }
        }

        private void ProcessFileContent(string filePath, string oldStr, string newStr)
        {
            try
            {
                // 读取文件内容
                string content = File.ReadAllText(filePath, Encoding.UTF8);
                // 替换内容
                content = content.Replace(oldStr, newStr);
                // 写回文件
                File.WriteAllText(filePath, content, Encoding.UTF8);
                this.textBox1.Text += $"处理文件 {filePath} 完成" + "\n";
            }
            catch (Exception ex)
            {
                this.textBox1.Text += $"处理文件 {filePath} 时出错: {ex.Message}" + "\n";
            }
            this.textBox1.Text += "\n\n";
        }




        private void SaveData()
        {
            //将数据内容保存到json文本中
            MySettings settings = new MySettings();
            settings.BlackProgramDir = this.BlackProgramDirText.Text;
            settings.TargetDir = this.targetDirText.Text;
            settings.ServerItems = new Dictionary<string, bool>();
            if (this.itemControls.Count > 0)
            {
                foreach (var itemControl in this.itemControls)
                {
                    settings.ServerItems.Add(itemControl.GetServerName(), itemControl.GetCheckState() == CheckState.Checked);
                }
            }
            string json = JsonConvert.SerializeObject(settings);
            File.WriteAllText("data.json", json);
        }
        private void LoadData()
        {
            if (File.Exists("data.json"))
            {
                string json = File.ReadAllText("data.json");
                MySettings settings = JsonConvert.DeserializeObject<MySettings>(json);
                this.BlackProgramDirText.Text = settings.BlackProgramDir;
                this.targetDirText.Text = settings.TargetDir;
                itemControls.Clear();
                itemControls = new List<ServerItemControl>();
                flowLayoutPanel1.Controls.Clear();

                if (settings.ServerItems.Count > 0)
                {
                    List<string> serverNames = settings.ServerItems.Keys.ToList();
                    List<bool> serverChecks = settings.ServerItems.Values.ToList();
                    for (int i = 0; i < settings.ServerItems.Count; i++)
                    {
                        // 创建新的ItemControl
                        var newItem = new ServerItemControl();
                        // 添加到列表和面板
                        itemControls.Add(newItem);
                        flowLayoutPanel1.Controls.Add(newItem);
                        // 更新标签文本显示序号
                        newItem.Init(serverNames[i], serverChecks[i]);
                    }
                }
            }
        }
    }
}
